package cn.com.cetccst.compliancecheck.checker;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;

import cn.com.cetccst.compliancecheck.R;
import cn.com.cetccst.tools.log.CommonLogger;

public class SystemTimeChecker extends Checker {
    private static final int SETTING_MANUAL = 0;
    private static SystemTimeChecker instance;
    private final BroadcastReceiver timeUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) return;
            String action = intent.getAction();
            if (action == null || action.isEmpty()) return;
            CommonLogger.info("system date time changed;" + action);

            checkTimeResult(context);

            //状态发生变化，重新持久化
            CheckerManager.getInstance().saveChecker(SystemTimeChecker.this);
        }
    };

    private SystemTimeChecker(Context context) {
        super(CheckerType.SystemTime);
        name = context.getString(R.string.compliance_system_time);
        startMonitor(context);
    }

    public static void init(Context context) {
        if (instance == null) {
            instance = new SystemTimeChecker(context);
        }
    }

    public static SystemTimeChecker getInstance() {
        return instance;
    }

    @Override
    public void check(Context context) {
        CommonLogger.info("Start check system time change");

        checkTimeResult(context);
    }

    private void checkTimeResult(Context context) {
        super.check(context);
        if (!isEnable()) {
            return;
        }

        try {
            int autoTimevalue = Settings.Global.getInt(context.getContentResolver(), Settings.Global.AUTO_TIME);
            int autoTimeZonevalue = Settings.Global.getInt(context.getContentResolver(), Settings.Global.AUTO_TIME_ZONE);
            super.violationDetail = context.getString(R.string.violation_detail_autotime_or_timezone_off);

            boolean isTimeSync = autoTimevalue == SETTING_MANUAL;

            boolean isTimezoneSync = autoTimeZonevalue == SETTING_MANUAL;
            if (isTimeSync || isTimezoneSync) {
                setResult(CheckResult.Violated);
            }
        } catch (Exception e) {
            CommonLogger.error("occur Exception when read time setting", e);
        }
        setResult(CheckResult.Pass);
    }

    private void startMonitor(Context context) {

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        //filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        context.registerReceiver(timeUpdateReceiver, filter);
    }
}
